package us.team.openAnAppAtRandom;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import android.widget.CheckBox;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import us.team.openAnAppAtRandom.model.AppItem;
import us.team.openAnAppAtRandom.model.AppList;
import us.team.openAnAppAtRandom.util.AppListManager;

public class ListDetailActivity extends AppCompatActivity {
    
    private AppListManager appListManager;
    private AppList currentList;
    private int listPosition;
    private ListView listView;
    private AppAdapter adapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_detail);
        
        appListManager = new AppListManager(this);
        
        // 获取传递过来的清单位置
        listPosition = getIntent().getIntExtra("list_position", -1);
        if (listPosition == -1 || listPosition >= appListManager.getAppLists().size()) {
            Toast.makeText(this, "清单不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        currentList = appListManager.getAppLists().get(listPosition);
        
        // 设置标题和应用计数
        TextView tvListTitle = findViewById(R.id.tv_list_title);
        TextView tvAppCount = findViewById(R.id.tv_app_count);
        tvListTitle.setText(currentList.getName());
        updateAppCount();
        
        // 设置返回按钮
        Button btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> finish());
        
        // 设置添加应用按钮
        Button btnAddApp = findViewById(R.id.btn_add_app);
        btnAddApp.setOnClickListener(v -> showAppSelectionDialog());
        
        // 设置随机打开按钮
        Button btnRandomApp = findViewById(R.id.btn_random_app_from_list);
        btnRandomApp.setOnClickListener(v -> openRandomAppFromList());
        
        // 设置添加所有应用按钮
        Button btnAddAllApps = findViewById(R.id.btn_add_all_apps);
        btnAddAllApps.setOnClickListener(v -> addAllAppsToList());
        
        // 设置应用列表
        listView = findViewById(R.id.list_apps);
        adapter = new AppAdapter();
        listView.setAdapter(adapter);
    }
    
    private void openRandomAppFromList() {
        if (currentList.size() == 0) {
            Toast.makeText(this, "清单为空，请先添加应用", Toast.LENGTH_SHORT).show();
            return;
        }
        
        int randomIndex = new Random().nextInt(currentList.size());
        AppItem selectedApp = currentList.getApps().get(randomIndex);
        
        // 显示确认对话框
        showConfirmationDialog(selectedApp.getAppName(), selectedApp.getPackageName());
    }
    
    private void showConfirmationDialog(String appName, String packageName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(appName);
        builder.setMessage("？");
        
        final AlertDialog dialog = builder.create();
        
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认(3秒)", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                openApp(packageName);
            }
        });
        
        dialog.setButton(DialogInterface.BUTTON_NEUTRAL, "换一个", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                dialog.dismiss();
                openRandomAppFromList();
            }
        });
        
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int which) {
                dialog.dismiss();
            }
        });
        
        dialog.show();
    }
    
    private void openApp(String packageName) {
        PackageManager pm = getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(packageName);
        if (intent != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, "无法打开应用", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 更新应用计数显示
     */
    private void updateAppCount() {
        TextView tvAppCount = findViewById(R.id.tv_app_count);
        tvAppCount.setText(currentList.size() + " 个应用");
    }
    
    /**
     * 添加所有可用应用到清单
     */
    private void addAllAppsToList() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加所有应用");
        builder.setMessage("确定要添加所有可用应用到此清单吗？这可能会添加大量应用。");
        
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 显示加载对话框
                final AlertDialog loadingDialog = new AlertDialog.Builder(ListDetailActivity.this)
                    .setTitle("添加中...")
                    .setMessage("正在添加应用到清单，请稍候...")
                    .setCancelable(false)
                    .create();
                loadingDialog.show();
                
                // 在后台线程中处理
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        // 获取所有已安装的应用
                        PackageManager pm = getPackageManager();
                        List<PackageInfo> packages = pm.getInstalledPackages(0);
                        
                        // 创建已在清单中的应用包名集合，提高查找效率
                        java.util.Set<String> existingPackages = new java.util.HashSet<>();
                        for (AppItem item : currentList.getApps()) {
                            existingPackages.add(item.getPackageName());
                        }
                        
                        int addedCount = 0;
                        
                        for (PackageInfo pkg : packages) {
                            Intent launchIntent = pm.getLaunchIntentForPackage(pkg.packageName);
                            if (launchIntent != null && !pkg.packageName.equals(getPackageName())) {
                                // 使用HashSet快速检查是否已在清单中
                                if (!existingPackages.contains(pkg.packageName)) {
                                    String appName = "";
                                    try {
                                        ApplicationInfo appInfo = pm.getApplicationInfo(pkg.packageName, 0);
                                        appName = pm.getApplicationLabel(appInfo).toString();
                                    } catch (PackageManager.NameNotFoundException e) {
                                        appName = pkg.packageName;
                                    }
                                    
                                    currentList.addApp(new AppItem(appName, pkg.packageName));
                                    addedCount++;
                                }
                            }
                        }
                        
                        final int finalAddedCount = addedCount;
                        
                        // 在UI线程中更新界面
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loadingDialog.dismiss();
                                
                                if (finalAddedCount > 0) {
                                    appListManager.updateAppList(listPosition, currentList);
                                    adapter.notifyDataSetChanged();
                                    updateAppCount();
                                    Toast.makeText(ListDetailActivity.this, 
                                        "已添加 " + finalAddedCount + " 个应用", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(ListDetailActivity.this, 
                                        "没有可添加的应用", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                }).start();
            }
        });
        
        builder.setNegativeButton("取消", null);
        builder.show();
    }
    
    private void showAppSelectionDialog() {
        // 先显示加载对话框
        AlertDialog loadingDialog = new AlertDialog.Builder(this)
            .setTitle("加载中...")
            .setMessage("正在获取应用列表，请稍候...")
            .setCancelable(false)
            .create();
        loadingDialog.show();
        
        // 在后台线程中加载应用列表
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取所有已安装的应用
                PackageManager pm = getPackageManager();
                List<PackageInfo> packages = pm.getInstalledPackages(0);
                
                // 过滤掉系统应用和已在清单中的应用
                final List<AppItem> availableApps = new ArrayList<>();
                final List<Boolean> selectedApps = new ArrayList<>();
                
                // 创建已在清单中的应用包名集合，提高查找效率
                java.util.Set<String> existingPackages = new java.util.HashSet<>();
                for (AppItem item : currentList.getApps()) {
                    existingPackages.add(item.getPackageName());
                }
                
                for (PackageInfo pkg : packages) {
                    Intent launchIntent = pm.getLaunchIntentForPackage(pkg.packageName);
                    if (launchIntent != null && !pkg.packageName.equals(getPackageName())) {
                        // 使用HashSet快速检查是否已在清单中
                        if (!existingPackages.contains(pkg.packageName)) {
                            String appName = "";
                            try {
                                ApplicationInfo appInfo = pm.getApplicationInfo(pkg.packageName, 0);
                                appName = pm.getApplicationLabel(appInfo).toString();
                            } catch (PackageManager.NameNotFoundException e) {
                                appName = pkg.packageName;
                            }
                            
                            availableApps.add(new AppItem(appName, pkg.packageName));
                            selectedApps.add(false); // 默认不选中
                        }
                    }
                }
                
                // 在UI线程中显示对话框
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingDialog.dismiss();
                        
                        if (availableApps.isEmpty()) {
                            Toast.makeText(ListDetailActivity.this, "没有可添加的应用", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        
                        showAppSelectionDialogWithData(availableApps, selectedApps);
                    }
                });
            }
        }).start();
    }
    
    private void showAppSelectionDialogWithData(final List<AppItem> availableApps, final List<Boolean> selectedApps) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择要添加的应用");
        // 设置对话框背景为黑色
        builder.setInverseBackgroundForced(true);
        
        // 创建自定义布局
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_app_selection, null);
        builder.setView(dialogView);
        
        // 设置应用列表
        ListView appListView = dialogView.findViewById(R.id.list_apps_selection);
        final AppSelectionAdapter selectionAdapter = new AppSelectionAdapter(availableApps, selectedApps);
        appListView.setAdapter(selectionAdapter);
        
        // 设置搜索功能
        EditText etSearch = dialogView.findViewById(R.id.et_search_app);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 搜索过滤
                selectionAdapter.filter(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 不需要实现
            }
        });
        
        // 添加按钮
        builder.setPositiveButton("添加所选应用", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int addedCount = 0;
                for (int i = 0; i < availableApps.size(); i++) {
                    if (selectedApps.get(i)) {
                        currentList.addApp(availableApps.get(i));
                        addedCount++;
                    }
                }
                
                if (addedCount > 0) {
                    appListManager.updateAppList(listPosition, currentList);
                    adapter.notifyDataSetChanged();
                    updateAppCount(); // 更新应用计数
                    Toast.makeText(ListDetailActivity.this, 
                        "已添加 " + addedCount + " 个应用", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ListDetailActivity.this, 
                        "未选择任何应用", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        builder.setNegativeButton("取消", null);
        builder.show();
    }
    
    /**
     * 应用选择适配器
     */
    private class AppSelectionAdapter extends BaseAdapter {
        private List<AppItem> allApps; // 所有应用
        private List<AppItem> filteredApps; // 过滤后的应用
        private List<Boolean> allSelectedStatus; // 所有应用的选中状态
        private List<Integer> filteredIndices; // 过滤后应用在原列表中的索引
        
        public AppSelectionAdapter(List<AppItem> apps, List<Boolean> selectedStatus) {
            this.allApps = apps;
            this.allSelectedStatus = selectedStatus;
            this.filteredApps = new ArrayList<>(apps);
            this.filteredIndices = new ArrayList<>();
            for (int i = 0; i < apps.size(); i++) {
                filteredIndices.add(i);
            }
        }
        
        /**
         * 根据搜索文本过滤应用列表
         */
        public void filter(String searchText) {
            filteredApps.clear();
            filteredIndices.clear();
            
            if (searchText.isEmpty()) {
                // 如果搜索文本为空，显示所有应用
                filteredApps.addAll(allApps);
                for (int i = 0; i < allApps.size(); i++) {
                    filteredIndices.add(i);
                }
            } else {
                // 否则，只显示匹配的应用
                searchText = searchText.toLowerCase();
                for (int i = 0; i < allApps.size(); i++) {
                    AppItem app = allApps.get(i);
                    if (app.getAppName().toLowerCase().contains(searchText) || 
                        app.getPackageName().toLowerCase().contains(searchText)) {
                        filteredApps.add(app);
                        filteredIndices.add(i);
                    }
                }
            }
            
            notifyDataSetChanged();
        }
        
        @Override
        public int getCount() {
            return filteredApps.size();
        }
        
        @Override
        public Object getItem(int position) {
            return filteredApps.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return filteredIndices.get(position);
        }
        
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.item_app_selection, parent, false);
            }
            
            final AppItem app = filteredApps.get(position);
            final int originalIndex = filteredIndices.get(position);
            
            ImageView ivAppIcon = view.findViewById(R.id.iv_app_icon);
            TextView tvAppName = view.findViewById(R.id.tv_app_name);
            TextView tvPackageName = view.findViewById(R.id.tv_package_name);
            final CheckBox cbSelected = view.findViewById(R.id.cb_app_selected);
            
            // 设置应用图标
            try {
                Drawable icon = getPackageManager().getApplicationIcon(app.getPackageName());
                ivAppIcon.setImageDrawable(icon);
            } catch (PackageManager.NameNotFoundException e) {
                ivAppIcon.setImageResource(android.R.drawable.sym_def_app_icon);
            }
            
            tvAppName.setText(app.getAppName());
            tvPackageName.setText(app.getPackageName());
            cbSelected.setChecked(allSelectedStatus.get(originalIndex));
            
            // 设置点击事件
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean newStatus = !allSelectedStatus.get(originalIndex);
                    allSelectedStatus.set(originalIndex, newStatus);
                    cbSelected.setChecked(newStatus);
                }
            });
            
            cbSelected.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    allSelectedStatus.set(originalIndex, cbSelected.isChecked());
                }
            });
            
            return view;
        }
    }
    
    /**
     * 清单中应用列表适配器
     */
    private class AppAdapter extends BaseAdapter {
        
        @Override
        public int getCount() {
            return currentList.getApps().size();
        }
        
        @Override
        public Object getItem(int position) {
            return currentList.getApps().get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getLayoutInflater().inflate(R.layout.item_app, parent, false);
            }
            
            final AppItem app = currentList.getApps().get(position);
            
            ImageView ivAppIcon = view.findViewById(R.id.iv_app_icon);
            TextView tvAppName = view.findViewById(R.id.tv_app_name);
            TextView tvPackageName = view.findViewById(R.id.tv_package_name);
            Button btnOpenApp = view.findViewById(R.id.btn_open_app);
            Button btnRemoveApp = view.findViewById(R.id.btn_remove_app);
            
            // 设置应用图标
            try {
                Drawable icon = getPackageManager().getApplicationIcon(app.getPackageName());
                ivAppIcon.setImageDrawable(icon);
            } catch (PackageManager.NameNotFoundException e) {
                ivAppIcon.setImageResource(android.R.drawable.sym_def_app_icon);
            }
            
            tvAppName.setText(app.getAppName());
            tvPackageName.setText(app.getPackageName());
            
            // 设置打开按钮点击事件
            btnOpenApp.setOnClickListener(v -> {
                openApp(app.getPackageName());
            });
            
            // 设置移除按钮点击事件 - 直接移除，不显示确认对话框
            btnRemoveApp.setOnClickListener(v -> {
                currentList.removeApp(position);
                appListManager.updateAppList(listPosition, currentList);
                notifyDataSetChanged();
                updateAppCount(); // 更新应用计数
                Toast.makeText(ListDetailActivity.this, "已移除应用", Toast.LENGTH_SHORT).show();
            });
            
            return view;
        }
    }
}